package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.ApThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * es文章分页检索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {

        ApUser user = ApThreadLocal.getApUser();

        //异步调用 保存搜索记录
        if(user != null && dto.getFromIndex() == 0){
            apUserSearchService.insert(dto.getSearchWords(), user.getId());
        }

        //2.创建搜索请求对象，并且指定索引库
        SearchRequest searhRequest=new SearchRequest("app_info_article");
        BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();
        //关键字查询
        if(dto.getSearchWords()!=null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("all",dto.getSearchWords()));
        }
        //小于最小时间
        if(dto.getMinBehotTime()!=null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
        }

        searhRequest.source().query(boolQueryBuilder);

        //分页
        searhRequest.source().from(0).size(dto.getPageSize());

        //排序
        searhRequest.source().sort("publishTime", SortOrder.DESC);

        //高亮
        HighlightBuilder highlight=new HighlightBuilder();
        highlight.field("title");
        highlight.requireFieldMatch(false);
        highlight.preTags("<font style='color: red; font-size: inherit;'>");
        highlight.postTags("</font>");
        searhRequest.source().highlighter(highlight);

        //1.调用es的搜索api
        SearchResponse response = restHighLevelClient.search(searhRequest, RequestOptions.DEFAULT);
        //3. 结果封装
        return result(response);

    }
    /**
     * 抽取的封装结果的方法
     * @param response
     * @return
     */
    private ResponseResult result(SearchResponse response) {

        List<Map> list=new ArrayList<>();

        //获取命中的结果
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            //获取查询结果，返回是map集合
            Map<String, Object> map = hit.getSourceAsMap();
            //高亮数据封装
            //如果高亮域中有值
            if(hit.getHighlightFields().size()>0){
                //取出高亮域
                Text[] titles = hit.getHighlightFields().get("title").fragments();
                if(titles.length>0){
                    //把高亮之后的h_tile=<font>测试</font>
                    map.put("h_title",titles[0].toString());
                }
            }else{
                //表示没有高亮域，我们则把h_title=测试
                map.put("h_title",map.get("title"));
            }
            //把获取的结果封装到list
            list.add(map);
        }
        return  ResponseResult.okResult(list);
    }
}